﻿using System;
using System.Collections.Generic;
using System.Linq;
using good1.ApplicationServices.Interface;
using good1.Core;
using SharpArch.Core;
using SharpArch.Core.PersistenceSupport;

namespace good1.ApplicationServices
{
    //TODO some caching of charities, they're quite static
    public class CharityService : ICharityService
    {
        public CharityService(IRepository<Charity> charityRepository)
        {
            Check.Require(charityRepository != null, "charityRepository may not be null");

            this.charityRepository = charityRepository;
        }

        public IList<Charity> GetAllSorted()
        {
            IQueryable<Charity> charities = charityRepository.GetAll().AsQueryable();
            return charities.OrderBy(i => i.CharityName).ToList();
        }

    

        public Charity Get(int id)
        {
            return charityRepository.Get(id);
        }

        public IList<Charity> GetAll()
        {
            throw new NotImplementedException();
        }

        public IList<Charity> FindAll(IDictionary<string, object> propertyValuePairs)
        {
            throw new NotImplementedException();
        }

        public Charity FindOne(IDictionary<string, object> propertyValuePairs)
        {
            throw new NotImplementedException();
        }

        public Charity SaveOrUpdate(Charity entity)
        {
           return  charityRepository.SaveOrUpdate(entity);
        }

        public void Delete(Charity entity)
        {
            charityRepository.Delete(entity);
        }

        public string Delete(int id)
        {
            string resultMessage = "The charity was successfully deleted.";
            Charity charityToDelete = Get(id);

            if (charityToDelete != null)
            {
                Delete(charityToDelete);

                try
                {
                    DbContext.CommitChanges();
                }
                catch
                {
                    resultMessage = "A problem was encountered preventing the charity from being deleted. " +
                        "Another item likely depends on this charity.";
                    DbContext.RollbackTransaction();
                }
            }
            else
            {
                resultMessage = "The charity could not be found for deletion. It may already have been deleted.";
            }
            return resultMessage;
        }

        public IDbContext DbContext
        {
            get {return  charityRepository.DbContext; }
        }

                

        private readonly IRepository<Charity> charityRepository;
    }
}
